<?php

namespace app\index\controller;

use app\index\controller\BaseController;
use Curl\Curl;
use think\Config;
use think\Db;
use think\Request;

/**
 * 组织架构
 * Class Industry
 * @package app\index\controller
 */
class Organization extends BaseController
{
    /**
     * 部门list
     */
    public function dptList()
    {
        $id=(int)$this->request->get('id');
        $obj = db('department');
        if (empty($id)){
            $result=$obj->column('*','id');
            $position=db('position')
                ->column('p_id,belong','id');

            $user=db('user')
                ->where('status',1)
                ->where('rolo_id','neq',-1)
                ->group('rolo_id')
                ->column('count(id) as count','rolo_id');

            foreach ($position as $k=>$value){
                $position[$k]['count']=isset($user[$k]) ?$user[$k] :0;
                unset($value['p_id']);
            }
            foreach ($position as $value) {
                if (!isset($result[$value['belong']]['count'])) {
                    $result[$value['belong']]['count'] = 0;
                }
                $result[$value['belong']]['count'] += $value['count'];
            }
            unset($position,$user);
            foreach ($result as $item){
                $ids=get_child_ids($result,$item['id']);
                array_push($ids,$item['id']);
                foreach ($ids as $id){
                    if (!isset($result[$item['id']]['sum'])){
                        $result[$item['id']]['sum']=0;
                    }
                    if (!isset($result[$id]['count'])){
                        $result[$id]['count']=0;
                    }
                    $result[$item['id']]['sum']+=$result[$id]['count'];
                }
                $result[$item['id']]['count']=$result[$item['id']]['sum'];
                unset($result[$item['id']]['sum']);
            }
            $result = $this->getBusiness('common')->betree($result);
            return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $result));
        }
        $result=$obj->column('*','id');
        $ids = tree_son($result, $id);
        $ids = array_column($ids, 'id');
        array_push($ids, $id);
        foreach ($ids as $val) {
            unset($result[$val]);
        }
        $result = $this->getBusiness('common')->betree($result);
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $result));
    }

    /**
     * 部门add
     */
    public function dptAdd()
    {
        $reqDada['dpt_name'] = $this->request->get('dpt_name', '', 'trim');
        $reqDada['p_id'] = $this->request->get('p_id', 0, 'intval');

        Db::startTrans();
        try {
            Db::table('cq_department')->insert($reqDada);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

    /**
     * 部门detail
     */
    public function dptDetail()
    {
        $id = $this->request->get('id', null, 'intval');
        $single = db('department')->where('id', $id)->find();
        if (empty($single)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        $dpt=db('department')->field('id,p_id')->select()->toArray();
        $ids=get_top_parentid($dpt,$id);
        $ids=array_column($ids,'id');
        $key=array_search($id ,$ids);
        array_splice($ids,$key,1);
        $single['ids']=$ids;
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $single));
    }

    /**
     * 部门edit
     */
    public function dptEdit()
    {
        $id = $this->request->get('id', null, 'intval');
        $reqData['dpt_name'] = $this->request->get('dpt_name', null, 'trim');
        $reqData['p_id'] = $this->request->get('p_id', 0, 'intval');

        $result = db('department')->where('id', $id)->find();
        if (empty($result)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        Db::startTrans();
        try {
            Db::table('cq_department')->where(['id' => $id])->update($reqData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'update失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

    /**
     * 部门del
     */
    public function dptDel()
    {
        $id = $this->request->get('id', null, 'intval');
        $single = db('department')->where('id', $id)->find();
        if (empty($single)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        /****把子类部门和部门全删了****/
        $result=db('department')->field('id,p_id as pid')->select()->toArray();
        $ids=get_all_child($result, $id);
        array_push($ids,$id);
        /****数据库update****/
        Db::startTrans();
        try {
            //部门
            Db::table('cq_department')->whereIn('id',$ids)->delete();
            //部门对应职位
            Db::table('cq_position')->whereIn('belong',$ids)->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'del失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

    /**
     *  职位add
     */
    public function posAdd()
    {
        $reqData['position_name']=$this->request->get('position_name','','trim');
        $reqData['p_id']=$this->request->get('p_id',0,'intval');
        $reqData['belong']=$this->request->get('belong',0,'intval');

        Db::startTrans();
        try {
            Db::table('cq_position')->insert($reqData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'add失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

    /**
     *  职位list
     */
    public function posList()
    {
        $id=(int)$this->request->get('id');
        $obj = db('position a')->join('department b','a.belong=b.id','left');
        if (empty($id)){
            $result=$obj->field('a.*,b.dpt_name')->select()->toArray();
            $result = $this->getBusiness('common')->betree($result);
            return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $result));
        }
        $result=$obj->column('a.id,a.position_name,a.p_id,a.belong,b.dpt_name','a.id');
        $ids=tree_son($result,$id);
        $ids=array_column($ids,'id');
        array_push($ids,$id);
        foreach ($ids as $val){
            unset($result[$val]);
        }
        $result = $this->getBusiness('common')->betree($result);
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $result));
    }

    /**
     * 职位edit
     */
    public function posEdit()
    {
        $id = $this->request->get('id', null, 'intval');
        $reqData['position_name'] = $this->request->get('position_name', null, 'trim');
        $reqData['p_id'] = $this->request->get('p_id', 0, 'intval');
        $reqData['belong']=$this->request->get('belong',0,'intval');

        $result = db('position')->where('id', $id)->find();
        if (empty($result)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        Db::startTrans();
        try {
            Db::table('cq_position')->where(['id' => $id])->update($reqData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'update失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

    /**
     * 职位detail
     */
    public function posDetail()
    {
        $id = $this->request->get('id', null, 'intval');
        $single = db('position')->where('id', $id)->find();
        if (empty($single)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        /*****部门ids*****/
        $dpt=db('department')->field('id,p_id')->select()->toArray();
        $ids=get_top_parentid($dpt,$single['belong']);
        $ids=array_column($ids,'id');
//        dd($ids);
//        $key=array_search($id ,$ids);
//        array_splice($ids,$key,1);
        $single['dpt_ids']=$ids;
        /*****职务ids*****/
        $dpt=db('position')->field('id,p_id')->select()->toArray();
        $ids=get_top_parentid($dpt,$id);
        $ids=array_column($ids,'id');
        $key=array_search($id ,$ids);
        array_splice($ids,$key,1);
        $single['ids']=$ids;
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => $single));
    }
    
    /**
     * 职位del
     */
    public function posDel()
    {
        $id = $this->request->get('id', null, 'intval');
        $single = db('position')->where('id', $id)->find();
        if (empty($single)) {
            return json_encode(array('status' => -1, 'msg' => 'error', 'data' => []));
        }
        $result=db('position')->field('id,p_id as pid')->select()->toArray();
        $ids=get_all_child($result, $id);
        array_push($ids,$id);
        /****数据库update****/
        Db::startTrans();
        try {
            Db::table('cq_position')->whereIn('id',$ids)->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->result['status'] = -1;
            $this->result['msg'] = 'del失败';
            return $this->result;
        }
        return json_encode(array('status' => 1, 'msg' => 'success', 'data' => []));
    }

}